<template>
    <div class="system-role">
        <!--系统角色-->
        <Headline :headline1="$t('m.SystemManagement')+'  /  '" :headline2="$t('m.RoleAuthorization')"/>
        <a-card style="width: 100%">
            <!-- 操作部分 -->
            <div class="search-role">
                <div class="search-new-delete">
                    <div>
                        <a-input-search
                                class="a-input"
                                :placeholder="$t('m.PleaseEnterRoleName')"
                                style="width: 200px"
                                v-model="rolefrom.key"
                                @search="impotlistSearch"
                        />
                    </div>
                    <div class="new-delete">
                        <a-button
                                @click="addpower"
                                type="primary"
                                icon="plus"
                                style="width: 100%; height: 32px"
                                v-if="isTrue('sys:role:add')"
                        >
                            {{$t('m.NewRole')}}
                        </a-button>
                    </div>
                </div>
            </div>
            <div class="conter-table">
                <div id="components-table-demo-size">
                    <a-table
                            style="margin-top: 30px"
                            :rowKey="(r, i) => i.toString()"
                            :columns="columns"
                            :data-source="datas"
                            bordered
                            :pagination="false"
                    >
                        <div slot="tags" slot-scope="text, tags, i">
                            <a-button
                                    class="btn"
                                    style="
                  background-color: #67c23a;
                  border-color: #67c23a;
                  color: white;"
                                    icon="plus"
                                    @click="changed(text, tags, i)"
                                    :disabled="!isTrue('sys:role:auth')"
                            >{{$t('m.Authorization')}}
                            </a-button
                            >
                            <a-button
                                    class="btn"
                                    type="primary"
                                    icon="edit"
                                    @click="edits(text, tags, i)"
                            >{{$t('m.Modification')}}
                            </a-button
                            >
                            <a-button
                                    class="btn"
                                    type="danger"
                                    icon="delete"
                                    :disabled="!isTrue('sys:role:del')"
                                    @click="impodelete(text, tags, i)"
                            >{{$t('m.Delete')}}
                            </a-button
                            >
                        </div>
                    </a-table>
                    <a-pagination
                            class="pages"
                            show-size-changer
                            :defaultPageSize="5"
                            :default-current="1"
                            :total="total"
                            @change="poserPages"
                            :pageSizeOptions="['5', '10', '30', '40']"
                            @showSizeChange="onShowpowerChange"
                    />
                </div>
            </div>
        </a-card>
        <Drawer ref="drawer"></Drawer>
        <Modal :modal="modal" @modalLast="changedpower" @modalhand="powerhand">
            <a-form :form="form"  >
                <a-form-item class="modalItem" :label="$t('m.RoleNumber')">
                    <a-input
                        v-decorator="['roleCode',{ rules: [{ required: true, message: '请输入角色编号' }] }]"
                            style="width: 400px"
                            :placeholder="$t('m.PlaseEnterRoleNumber')"
                            v-model="addform.roleCode"
                            :disabled="inputs"
                    />
                </a-form-item>
                <a-form-item class="modalItem" :label="$t('m.CharacterName')">
                    <a-input
                        v-decorator="['roleName',{ rules: [{ required: true, message: '请输入角色名称' }] },]"
                        style="width: 400px"
                            :placeholder="$t('m.PleaseEnterRoleName')"
                            v-model="addform.roleName"
                    />
                </a-form-item>
            </a-form>
        </Modal>
        <Modal :modal="modals" @modalLast="addspower" @modalhand="changhand">
            <a-tree
                    checkable
                    v-model="roleMenuIdList"
                    :replace-fields="replaceFields"
                    :tree-data="treeData"
                    @check="onCheck"
            />
        </Modal>
        <Delete ref="powerdelete" :dalete="dalete" @confirm="powerdelete"></Delete>
    </div>
</template>

<script>
    import Headline from "@/components/Headline";
    import Drawer from "@/components/Drawer";
    import Modal from "@/components/common/Modal";
    import Delete from "@/components/Delete";
    import {Setperms} from "@/assets/js/setperms";
    import {
        getDelRole,
        getRoleList,
        getRoleMenuTreeByRoleId,
        getSaveRole,
        getSaveRoleMenu,
        getSysMenuList,
    } from "@/api/User";
    import {findTreeArr} from "@/assets/js/tree";

    export default {
        name: "Homeimpower",
        components: {Headline, Drawer, Modal, Delete},
        data() {
            return {
                form: this.$form.createForm(this, {name: 'coordinated'}),
                columns: [
                    {
                        title: this.$t('m.SerialNumber'),
                        dataIndex: "index",
                        key: "index",
                        customRender: (text, record, index) => `${index + 1}`,
                    },
                    {
                        title: this.$t('m.RoleNumber'),
                        dataIndex: "roleCode",
                    },
                    {
                        title: this.$t('m.CharacterName'),
                        dataIndex: "roleName",
                    },
                    {
                        title: this.$t('m.Operation'),
                        key: "tags",
                        dataIndex: "address",
                        scopedSlots: {customRender: "tags"},
                    },
                ],
                replaceFields: {
                    title: "menuName",
                    key: "menuId",
                    children: "children",
                },
                treeData: [],
                expandedKeys: ["0-0-0", "0-0-1"],
                checkedKeys: ["0-0-0"],

                autoExpandParent: true,
                inputs: false,
                datas: [],
                total: 0,
                modal: {
                    visible: false,
                    width: "600px",
                    title: this.$t('m.NewRole'),
                },
                modals: {
                    visible: false,
                    width: "600px",
                    title: this.$t('m.NewAuthorization'),
                },
                rolefrom: {
                    start: 0,
                    limit: 10,
                    page: 1,
                },
                addform: {
                    roleId: 0,
                    roleCode: "",
                    roleName: "",
                },
                roleMenuIdList: [],
                powerId: "", //删除id
                roleIdform: {
                    roleId: "",
                    roleMenuIdList: [],
                },
                dalete: {
                    titles: this.$t('m.DeleteThePrompt'),
                    type: "exclamation-point             ",
                    text: this.$t('m.AreYouSureToDeleteThisData'),
                },
            };
        },
        created() {
            this._getRoleList();
            this._getSysMenuList();
            this.parms = Setperms(
                this.$route.fullPath,
                JSON.parse(sessionStorage.getItem("menu"))
            );
            console.log(this.parms);
        },
        methods: {
            isTrue(str) {
                return this.parms.indexOf(str) !== -1;
            },
            _getRoleList() {
                getRoleList({params: this.rolefrom}).then((res) => {
                    if (res.data.success) {
                        this.datas = res.data.data;
                        this.$message.success("获取角色信息成功");
                        this.total = res.data.total;
                    }
                });
                this.inputs = false;
            },
            _getSysMenuList() {
                getSysMenuList().then((res) => {
                    console.log(res);
                    this.treeData = res.data.data;
                });
            },
            //搜索
            impotlistSearch() {
                this._getRoleList();
            },
            //新增角色
            addpower() {
                this.addform.roleName= "";
                this.addform.roleCode= "";
                this.addform.roleId= 0;
                this.modal.title = this.$t('m.NewRole');
                this.modal.visible = true;
            },
            //新增角色弹窗按钮点击
            changedpower() {
              this.form.validateFields(err => {
                if (!err) {
                  this.form.resetFields();
                  console.info('success');
                }
              });
                if (this.addform.roleCode != "" && this.addform.roleName != "") {
                    getSaveRole(this.addform).then((res) => {
                        this._getRoleList();
                    });
                    this.modal.visible = false;
                }
                this.form.resetFields();
            },
            powerhand() {
                this.modal.visible = false;
                this.inputs = false;
                this.addform.roleCode = "";
                this.addform.roleName = "";
                this.addform.roleId = 1;
                this.form.resetFields();
            },

            edits(text, tags, i) {
              console.log(tags)
              setTimeout(() => {
                this.form.setFieldsValue({
                  roleCode:tags.roleCode,
                  roleName:tags.roleName,
                  custId:tags.custId,
                  roleId:tags.roleId,
                  status:tags.status,
                })
              }, 200);
                console.log(tags);
                this.modal.title = this.$t('m.EditRole');
                this.inputs = true;
                this.modal.visible = true;
                this.addform.roleCode = tags.roleCode;
                this.addform.roleName = tags.roleName;
                this.addform.roleId = tags.roleId;
            },
            //删除点击
            impodelete(text, tags, i) {
                console.log(tags);
                this.powerId = tags.roleId;
                this.$refs.powerdelete.visible = true;
            },
            //删除确定
            powerdelete() {
                getDelRole({roleId: this.powerId}).then((res) => {
                    console.log(res);
                    this._getRoleList();
                });
                this.$refs.powerdelete.visible = false;
            },
            //授权
            changed(text, tags, i) {
                this.roleIdform.roleId = tags.roleId;
              console.log(this.roleIdform.roleMenuIdList)
              let arr;
                var menu = [];
                getRoleMenuTreeByRoleId({params: {roleId: tags.roleId}}).then(
                    (res) => {
                        this.modals.visible = true;
                    }
                );
            },
            //授权确定
            addspower() {
                // console.log(JSON.parse(JSON.stringify(this.roleIdform.roleMenuIdList)))
                console.log(this.roleIdform.roleMenuIdList);
                getSaveRoleMenu({
                    roleId: this.roleIdform.roleId,
                    // roleMenuIdList: JSON.parse(
                    //     JSON.stringify(this.roleIdform.roleMenuIdList)
                    // ),
                })
                    .then((res) => {
                        if (res.data.success) {
                            this.$message.success("角色授权成功");
                        } else {
                            this.$message.error("角色授权失败");
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
                this.roleIdform.roleMenuIdList = [];
                this.modals.visible = false;
            },
            //授权取消
            changhand() {
                this.roleIdform.roleMenuIdList = [];
                this.modals.visible = false;
            },
            //树形控件方法
            onCheck(checkedKeys, checkedNodes) {
                console.log(checkedKeys, checkedNodes);
                let mergeArr = [...checkedKeys, ...checkedNodes.halfCheckedKeys]
              console.log(111111111111111)
              console.log(mergeArr)
              console.log(222222222222222)
                let arr = JSON.parse(JSON.stringify(checkedKeys));
                // let str = arr.join(",");
                this.roleIdform.roleMenuIdList = mergeArr.join(",");
                this.roleMenuIdList = arr;
            },
            //分页
            onShowpowerChange(page, pageSize) {
                this.rolefrom.page = page;
                this.rolefrom.limit = pageSize;
                this.rolefrom.start = (page - 1) * pageSize;
                this._getRoleList();
            },
            poserPages(page, limit) {
                console.log(page, limit);
                this.rolefrom.page = page;
                this.rolefrom.limit = limit;
                this.rolefrom.start = (page - 1) * limit;
                this._getRoleList();
            },
        },
    };
</script>

<style scoped lang="css">
    .system-role {
        width: 100%;
        height: 100%;
    }

    .search-role {
        width: 100%;
    }

    .search-new-delete {
        display: flex;
    }

    button {
        /* margin-right: 10px; */
    }

    .a-input {
        margin-right: 15px;
    }

    .modalItem {
        display: flex;
        margin-top: 20px;
        justify-content: center;
    }

    .pages {
        margin-top: 15px;
    }

    .btn {
        margin-left: 15px;
    }
    .labelOk {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
    }
</style>
